<?php

namespace App\Http\Controllers\Admin;

use App\Events\UpdateMenuSession;
use App\Models\AdminPermission;
use App\Models\AdminRole;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Event;
use League\Flysystem\Exception;

class AdminRoleController extends Controller
{
    //
    /**
     *  角色列表
     */
    public function index()
    {
        
        return view('admin.admin_role.index');
    }

    public function indexPost(Request $request)
    {
        $input = $request->all();
        $dd = (new AdminRole())->dataTable(['*'], $input ,[
            'condition' => [
                [
                    'where',
                    ['where', 'name like %?%'],
                ]
            ]
        ]);
        return response()->json($dd);
    }

    /**
     *
     *  添加角色
     */
    public function addRole()
    {

        return view('admin.admin_role.addRole');
    }

    public function addRolePost(Request $request)
    {
        $input = [
          'name' => $request->input('name'),
           'description' => $request->input('description','')
        ];
        $info = AdminRole::where('name',$input['name'])->first();
        if(!empty($info)){
            return response()->json(['code'=>0,'msg'=>'角色已存在']);
        }
        $re = (new AdminRole())->create($input);
        if($re){
            return response()->json(['code'=>1,'msg'=>'成功']);
        }else{
            return response()->json(['code'=>0,'msg'=>'失败']);
        }
    }
    
    /**
     * 
     *  删除角色
     */
    public function delRole(Request $request)
    {
        $id = $request->input('id');
        $res = AdminRole::find($id)->delete();
        if($res){
            return response(['code'=>1,'msg'=>'成功']);
        }else{
            return response(['code'=>0,'msg'=>'失败']);
        }
    }

    /**
     *  角色授权
     */
    public function rolePermission($role_id)
    {
        $all_permission = (new AdminPermission())->arrayAllPermission();
        $ids = []; //用来存放显示角色已存在的pessmison_id;
        $role_permission = AdminRole::find($role_id)->permissions()->get();
        if(!empty($role_permission)){
            foreach ($role_permission as $k=>$v){
                $ids[] = $v->id;
            }
            $ids = implode(',',$ids);
        }

        return view('admin.admin_role.rolePermission',['role_id'=>$role_id, 'all_permission' => $all_permission,'ids' => $ids]);
    }

    public function rolePermissionPost(Request $request)
    {
        $p_ids = explode(',',$request->input('p_ids'));
        try{
            AdminRole::find($request->input('role_id'))->authorizePermissions($p_ids);
        }catch (Exception $e){
            return response()->json(['code'=>0 ,'msg'=>'失败']);
        }
        //更新权限缓存
        event(new UpdateMenuSession());

        return response()->json(['code'=>1 ,'msg'=>'成功']);
    }

}
